package main

import (
	"fmt"
	"gin_wuwen_back/controller"
	"gin_wuwen_back/mqtts"
	"gin_wuwen_back/tool"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)
import _ "github.com/go-sql-driver/mysql"

func main() {
	cfg, err := tool.ConfigJsonReader("./config/app.json") //读取配置文件
	if cfg.AppMode=="online" {
		cfg, err = tool.ConfigJsonReader("./config/app_online.json")
	}
	if err != nil {
		fmt.Println(err.Error())
		panic(err.Error())
	}
	_, errs := tool.OrmEngine(cfg)
	if errs != nil {
		fmt.Println("1111")

		fmt.Println(errs.Error())
		return
	}
	tool.InitRedisHome()

	engin := gin.Default() //返回值就是一个指针的类型
	engin.Static("/static", "./static")
	tool.InitSession(engin)
	engin.Use(Cors()) //调用跨域请求中间件
	RegisterRouter(engin)
	//初始化mqtt协议
	mqtts.InitMqtt()
	//提前定义好自己的主题名称，其他客户端按照这个名字给你发送消息
	mqtts.Sub(mqtts.Client)
	//mqtts.Sub2(mqtts.Client)
	engin.Run(cfg.AppIP + ":" + cfg.AppPort)

}

//将我们自己编写的路由管理模块注册一下
func RegisterRouter(engin *gin.Engine) {
	new(controller.RouterControl).Router(engin) //实例化我们编写好的路由管理器，
	// 调用方法将我们的引擎传入，至始至终我们都用的这一个引擎

}

//中间件解决跨域请求，其实也可以封装个方法
func Cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		origin := context.Request.Header.Get("Origin")
		var headerKeys []string
		for k, _ := range context.Request.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ",")
		if headerStr != "" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}

		if origin != "" {
			context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
			context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
			context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
			context.Header("Access-Control-Max-Age", "172800")
			context.Header("Access-Control-Allow-Credentials", "false")
			context.Set("content-type", "application/json") //// 设置返回格式是json
		}

		if method == "OPTIONS" {
			context.JSON(http.StatusOK, "Options Request!")
		}
		//处理请求
		context.Next()
	}
}
